package core;

import java.util.HashMap;

/**
 * @Author: Gosin
 * @Date: 2020/5/22 1:36
 */
public class LRUCache {
    private int capacity;
    private HashMap<Integer,DLikedNode> map = new HashMap<>();
    private DLikedNode head;
    private DLikedNode tail;
    class DLikedNode{
        int key;
        int value;
        DLikedNode pre;
        DLikedNode next;
    }
    public LRUCache(int capacity) {
        this.capacity = capacity;
        head = new DLikedNode();
        tail = new DLikedNode();
        head.next = tail;
        tail.pre = head;
    }
    private void addNode(DLikedNode node){
        map.put(node.key,node);
        tail.pre.next = node;
        node.pre = tail.pre;
        node.next = tail;
        tail.pre = node;
    }
    private void removeNode(DLikedNode node){
        map.remove(node.key);
        node.pre.next = node.next;
        node.next.pre = node.pre;
    }

    public int get(int key) {
        DLikedNode temp = map.get(key);
        if(null == temp){
            return -1;
        }else{
            //将temp移到尾部
            this.removeNode(temp);
            this.addNode(temp);
            return temp.value;
        }
    }

    public void put(int key, int value) {
        // 先判断是否是已经纯在的了
        DLikedNode temp = map.get(key);
        if(temp !=null) {
            temp.value = value;
            this.removeNode(temp);
            this.addNode(temp);
            return;
        }
        temp = new DLikedNode();
        temp.key = key;
        temp.value = value;
        if(capacity<=0){
            //删除头部数据，在尾部新增一个node
            this.removeNode(head.next);
        }
        this.addNode(temp);
        this.capacity--;
    }
}
